Ext.define('CDR.widget.ProfileLine', {
	extend: 'Ext.container.Container',
	alias: 'widget.profileline',
	anchor: '100%',
	layout:'column',
	targetObject: null,
	targetPbx: null,
	initComponent: function() {
		var me = this;
		me.callParent();
		this.idfield = Ext.createWidget('hidden',{
			name: 'id'
		});
		this.sequence = Ext.createWidget('hidden',{
			name: 'sequence'
		});
		this.name = Ext.createWidget('textfield',{
			fieldLabel: 'Name',
			allowBlank: false,
			anchor:'96%',
			labelWidth: 45,
			name: 'name'
		});
		this.description = Ext.createWidget('textfield',{
			fieldLabel: 'Description',
			anchor:'96%',
			name:'description'
		});
		this.bytes = Ext.createWidget('numberfield',{
			fieldLabel: 'Bytes',
			allowBlank: false,
			anchor:'96%',
			labelWidth: 45,
			value: 1,
			maxValue: 99,
			minValue: 1,
			name:'numOfbyte'
		});
		this.remove = Ext.createWidget('button',{
			width:22,
			iconCls:'icon-delete',
			handler: function(){
				Ext.Ajax.request({
					scope: this,
					method: 'POST',
					url:'delete-profile?profileId=' + this.idfield.getValue(),
					success: function(){
						this.targetObject.remove(this, true);
						Ext.each(this.targetObject.items.items, function(it){
							if(typeof it.name == 'object'){
								it.sequence.setValue(this.targetObject.items.indexOf(it));
							}
						}, this);
						this.targetObject.currentSequence --;
					}
				});
			}, 
			scope: this
		});
		this.up = Ext.createWidget('button',{
			width:22,
			iconCls:'icon-up',
			handler: function(){
				var fromIndex = this.targetObject.items.indexOf(this);				
				if(fromIndex > 0){
					this.targetObject.move(fromIndex, fromIndex - 1);	
				}
				Ext.each(this.targetObject.items.items, function(it){
					if(typeof it.name == 'object'){
						it.sequence.setValue(this.targetObject.items.indexOf(it));
					}
				}, this);
			},
			scope: this
		});
		this.down = Ext.createWidget('button',{
			width:22,
			iconCls:'icon-down',
			handler: function(){
				var fromIndex = this.targetObject.items.indexOf(this);				
				if(fromIndex < this.targetObject.items.length - 1){
					this.targetObject.move(fromIndex, fromIndex + 1);	
				}
				Ext.each(this.targetObject.items.items, function(it){
					if(typeof it.name == 'object'){
						it.sequence.setValue(this.targetObject.items.indexOf(it));
					}
				}, this);
				
			},
			scope: this
		});
		
		this.add(this.idfield, this.sequence,
			Ext.create('Ext.container.Container', {
				columnWidth:.25,
				layout: 'anchor',
				items:[this.name]
			}),
			Ext.create('Ext.container.Container', {
				columnWidth:.52,
				layout: 'anchor',
				items:[this.description]
			}),
			Ext.create('Ext.container.Container', {
				columnWidth:.15,
				layout: 'anchor',
				items:[this.bytes]
			}),
			Ext.create('Ext.container.Container', {
				columnWidth:.08,
				layout: 'hbox',
				items:[this.up, this.down, this.remove]
			})
		);
		// init value
		var config = this.initialConfig;
		if(config.idfield){
			this.idfield.setValue(config.idfield);
		}
		if(config.name){
			this.name.setValue(config.name);
		}
		if(config.description){
			this.description.setValue(config.description);
		}
		if(config.bytes){
			this.bytes.setValue(config.bytes);
		}
		if(config.sequence){
			this.sequence.setValue(config.sequence);
		}
	}
});

Ext.define('CDR.widget.Profile', {
	extend: 'Ext.form.Panel',
	region:'center',
	alias:'widget.profile',
	title:'Profile',
	buttonAlign:'center',
	currentItem: null,
	bodyStyle:'padding:5px 5px 0',
	layout:'column',
    autoScroll:true,
    defaults: {
        layout: 'anchor',
        defaults: {
            anchor: '100%'
        }
    },
	fieldDefaults: {
		msgTarget: 'side',
		labelWidth: 65
	},
	initComponent: function(){
	   var me = this;
       me.callParent();
       
       this.itemSelector = Ext.createWidget('pbxItemselector', {
	        name: 'itemselector',
	        columnWidth: 1/2,
	        store: Ext.create('CDR.store.ProfileColumnStore'),
	        displayField: 'name',
	        valueField: 'obId',
	        border: true,
	        allowBlank: false,
	        msgTarget: 'side',
	        listeners:{
	        	afterrender: function(view) {
	        		var profile = view.up('profile');
	        		view.toField.boundList.on("itemclick", function(view, r){
			     		//popup value to field
			     		profile.currentItem = r;
			     		console.log(r);
			     		profile.down('numberfield[name=numOfbytes]').setValue(r.data.numOfbytes);
			     		profile.down('numberfield[name=space]').setValue(r.data.space);
			     		profile.down('combo').setValue(r.data.columnMapping);
			     	});
			     	
			     	//init data
			     	Ext.Ajax.request({
						url:'list-profile?pbxId=' + me.targetPbx.data.obId,
						success: function(response, opts){
							var obj = Ext.decode(response.responseText);
							if(obj.results){
								var data = obj.results;
								if(data.length > 0) {
									view.reloadToData(data);
									Ext.iterate(data, function(d){
										console.log("set data", d.name)
										if(d.obId == 'dateformat'){
											me.down('textfield[name=dateformat]').setValue(d.name);
										} else if(d.obId == 'durationformat'){
											me.down('textfield[name=durationformat]').setValue(d.name);
										} else if(d.obId == 'timeformat'){
											me.down('textfield[name=timeformat]').setValue(d.name);
										}
									});
								} 
							}
						}
					});
	        	}
	        }
	   });
	   
	   this.add(this.itemSelector);
	   this.add({
	   	xtype: 'container',
	   	columnWidth: 1/2,
	   	anchor: '100%',
	   	layout: 'anchor',
	   	padding:'15 15 15 15',
	   	items: [{
	   			xtype: 'numberfield',
	   			fieldLabel: 'Num of bytes',
	   			name:'numOfbytes',
	   			min: 0,
	   			flex: 1,
	   			labelWidth: 150,
	   			listeners: {
	   				change: function(comp, newValue){
	   					var profile = comp.up('profile');
	   					profile.currentItem.set("numOfbytes", newValue);
	   				}
	   			}
	   		},{
	   			xtype: 'numberfield',
	   			fieldLabel: 'Append Space',
	   			name:'space',
	   			min: 0,
	   			value: 1,
	   			flex: 1,
	   			labelWidth: 150,
	   			listeners: {
	   				change: function(comp, newValue){
	   					var profile = comp.up('profile');
	   					profile.currentItem.set("space", newValue);
	   				}
	   			}
	   		}, {
		   		xtype: 'textfield',
		   		labelWidth: 150,
		   		anchor: '100%',
		   		name: 'dateformat',
		   		fieldLabel: 'Date Format',
		   		value: 'MMddyy'
	   		}, {
		   		xtype: 'textfield',
		   		name: 'timeformat',
		   		labelWidth: 150,
		   		anchor: '100%',
		   		fieldLabel: 'Time Format',
		   		value: 'hhmmss'
	   		}, {
		   		xtype: 'textfield',
		   		name: 'durationformat',
		   		labelWidth: 150,
		   		anchor: '100%',
		   		fieldLabel: 'Duration Format',
		   		value: 'hmmss'
	   		}, {
		   		xtype: 'combo',
		   		name: 'columnMapping',
		   		labelWidth: 150,
		   		anchor: '100%',
		   		fieldLabel: 'Column Mapping',
		   		store: Ext.create('Ext.data.Store', {
		   			fields: [{name :'key'}, {name: 'text'}],
		   			data: [{key: '', text: 'None'},
		   			{key: 'def_start_date', text: 'Start call date'},
		   			{key: 'def_start_time', text: 'Start call time'},
		   			{key: 'def_duration', text: 'Duration of call'},
		   			{key: 'def_author_code', text: 'Employee code'},
		   			{key: 'def_calling_number', text: 'Calling number'},
		   			{key: 'def_dialed_number', text: 'Dialed number'},
		   			{key: 'def_trunk_no', text: 'Trunk No'}]
		   		}),
		   		valueField: 'key',
		   		displayField: 'text',
		   		listeners: {
	   				change: function(comp, newValue){
	   					var profile = comp.up('profile');
	   					profile.currentItem.set("columnMapping", newValue);
	   				}
	   			},
	   			value: ''
	   		} , {
		   		xtype: 'hidden',
		   		name: 'pbxId'
	   		}]
	   });
	   
	   this.itemSelector.store.load();
    },
	buttons:[{
		text: 'Save All',
		iconCls: 'icon-save',
		formBind: true,
		handler: function() {
			var form = this.up('form').getForm();
			if (form.isValid()) {
				//build submit value
				var store = this.up('form').itemSelector.toField.boundList.getStore();
				var profileData = [];
				store.each(function(r){
					profileData.push({column: r.data['obId'], name: r.data['name'], numOfbytes: r.data['numOfbytes'], space: r.data['space'], columnMapping: r.data['columnMapping']});
				});
				console.log(form.getValues());
				form.submit({
					params: {profileData: Ext.encode(profileData)},
					success: function(form, action) {
					   Ext.Msg.alert('Success', action.result.msg);
					},
					failure: function(form, action) {
						Ext.Msg.alert('Failed', action.result.msg);
					}
				});
			}
		}
	}],
	
	reloadData: function(sn) {
		this.targetPbx = sn;
		//set pbx id for hidden field
		this.down('hidden[name=pbxId]').setValue(sn.data.obId);
		var me = this;
		if(this.itemSelector.rendered){
			//init data
			this.itemSelector.bindStore(this.itemSelector.store); 
	     	Ext.Ajax.request({
				url:'list-profile?pbxId=' + me.targetPbx.data.obId,
				success: function(response, opts){
					var obj = Ext.decode(response.responseText);
					if(obj.results){
						var data = obj.results;
						if(data.length > 0) {
							me.itemSelector.reloadToData(data);
							//populate value for another field
							console.log("set data", data)
							Ext.iterate(data, function(d){
								console.log("set data", d.name)
								if(d.obId == 'dateformat'){
									me.down('textfield[name=dateformat]').setValue(d.name);
								} else if(d.obId == 'durationformat'){
									me.down('textfield[name=durationformat]').setValue(d.name);
								} else if(d.obId == 'timeformat'){
									me.down('textfield[name=timeformat]').setValue(d.name);
								}
							});
						} 
					}
				}
			});
		}
	}
	
});
